/**
 * 描述: 业务逻辑处理 - 单词接口
 * 作者: wz
 * 日期: 2023-12-25
*/


const { querySql, queryOne } = require('../utils/index');
const boom = require('boom');
const { body, validationResult } = require('express-validator');
const { 
  CODE_ERROR,
  CODE_SUCCESS, 
} = require('../utils/constant');
const fs = require('fs');
const path = require('path');
const request = require('request');

const AK = "mClVlfwqWSQeuqM1kaFyyR6B"
const SK = "AcXqiGdvJZ9u6yqqZy8dq9XqYbs5dMPE"
let g_access_token = '';
let g_expire_time = 0;

// 添加一个单词
async function editOneWord( table_name, addWords, user_id, book_id, is_add, newbook_id=0){
  let where_str = ' where 1';
  if( newbook_id > 0){
    where_str += ` and id=${newbook_id}`;
  }else{
    where_str += ` and user_id=${user_id} and book_id=${book_id}`;
  }
  let query = `select words from ${table_name}`;
  query += where_str;
  //console.log(query)
  let data = await querySql(query);
  if(data && data.length > 0){
    let words = [];
    if( data[0].words){
      words = data[0].words.split(',');
    }
    let bChange = false;
    for( let word of addWords){
      let index = words.findIndex(item => item === word);
      if(is_add){
        if(index < 0){            
          words.push(word);
          bChange = true;
        }
      }else{  
        if(index >= 0){
          words.splice(index, 1);
          bChange = true;
        }
      }
    }
    if( bChange ){
      let query1 = `update ${table_name} set words='${words.join(',')}'`
      if(is_add){
        query1 += `, gmt_create=now()`;
      }
      query1 += where_str;
      //console.log(query1)
      data = await querySql(query1);
    }
  }else if( book_id > 0){
    const query1 = `insert into ${table_name}(user_id, book_id, words) values('${user_id}', '${book_id}', '${addWords.join(',')}')`;
    data = await querySql(query1);
  }
  return data;
}

// 编辑词汇包生词
async function editNewWord(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { word, word_zh='', user_id, book_id=0, is_add=false, newbook_id=0} = req.body;

    try{
      word = word.replace(/['"\/\|\*?]/g, '’');
      let addWords = word.split(',');
      let data = await editOneWord('sys_newword', addWords, user_id, book_id, is_add, newbook_id);
      if( 0 == book_id){
        // 添加到每日学习
        // await editOneWord('sys_studyword', addWords, user_id, book_id, is_add);
        if( is_add){
          // 添加单词
          const query2 = `select word from sys_allword`;
          let allWords = await querySql(query2);
          let insertStr = [];
          for( let item of addWords){
            if( allWords.findIndex(i=>i.word==item) < 0){
              insertStr.push( `('${item}', '${word_zh}')`);
            }
          }
          if( insertStr.length > 0){
            const query3 = `insert into sys_allword(word, word_zh) values ${insertStr.join(',')}`;
            await querySql(query3);
          }
        }
      }
      res.json({ 
        code: CODE_SUCCESS, 
        msg: '添加数据成功', 
        data
      })
    }catch( err){
      console.log(err)
      res.json({ 
        code: CODE_ERROR, 
        msg: '添加数据失败', 
        data: err 
      })
    }
  }
}

async function getNewWord(user_id, book_id, newbook_id) {
  let query = 'select id,book_id,words,gmt_create,name from sys_newword'

  let params = ' where delete_flag=0';
  if( newbook_id){
    params += ' and id=' + newbook_id;
  }else{
    if(book_id != undefined){
      params += ' and book_id=' + book_id;
    }
    if(user_id){
      params += ' and user_id=' + user_id;
    }
  }
  //console.log(params)
  let data = await querySql(query + params)
  return data;
}

// 查询所有单词包列表
async function getNewWordList(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
    next(boom.badRequest(msg));
  } else {

    let { book_id, user_id, study_id, is_new=false, newbook_id=0 } = req.body;
    //console.log(req.body)
    try{
      let studyWords = '';
      let dataStudy = [];
      if( !is_new){
        let query = `select id,user_id,book_id,words from sys_studyword where 1 `;
        if( study_id ){
          query += `and id=${study_id}`;
        }else{
          query += `and user_id=${user_id} and book_id=${book_id}`;
        }
        dataStudy = await querySql(query);
        if( dataStudy && dataStudy.length >0 ){
          for( let i=0; i<dataStudy.length; i++){
            let item = dataStudy[i];
            user_id = item.user_id;
            book_id = item.book_id;
            studyWords += item.words;
            if( i < dataStudy.length -1 ){
              studyWords += ',';
            }
          }
        }
      }
      let data = await getNewWord(user_id, book_id, newbook_id);
    	// console.log('任务列表查询===', data);
      res.json({ 
        code: CODE_SUCCESS, 
        msg: '查询数据成功', 
        data: {
          rows: data,
          studyWords,
          dataStudy
        } 
      })
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '暂无数据', 
        data: err 
      })
    }
  }
}

/*
 * 使用 AK，SK 生成鉴权签名（Access Token）
 * @return string 鉴权签名信息（Access Token）
 */
function getAccessToken() {
  let options = {
      'method': 'POST',
      'url': 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + AK + '&client_secret=' + SK,
  }
  return new Promise((resolve, reject) => {
      request(options, (error, response) => {
          if (error) { reject(error) }
          else { 
            //console.log( response.body)
            resolve(JSON.parse(response.body) || {}) 
          }
      })
  })
}

function getOCR( image, access_token) {
  //let params = {image};
  //console.log(JSON.stringify(body));
  var options = {
      'method': 'POST',
      'url': 'https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=' + access_token,
      'headers': {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Accept': 'application/json'
      },
      body: 'language_type=ENG&image='+image
  };
  return new Promise((resolve, reject) => {
    request(options, function (error, response) {
        if (error) { reject(error) }
        else { 
          //console.log( response.body)
          resolve(JSON.parse(response.body) || {})
        }
    })
  })
}

// 查询方案列表
async function aiOCR(req, res, next) {
  const err = validationResult(req);
  // 如果验证错误，empty不为空
  if (!err.isEmpty()) {
    // 获取错误信息
    const [{ msg }] = err.errors;
    // 抛出错误，交给我们自定义的统一异常处理程序进行错误返回 
    next(boom.badRequest(msg));
  } else {
    let {user_id=0, image} = req.body;
    if( !user_id){
      res.json( { 
        code: CODE_ERROR, 
        msg: '参数错误', 
        data: err
      });
      return;
    }
    try{
      const query1 = `select count(user_id) as scan_count from sys_scanlog where DATE(gmt_create) = CURDATE() and user_id=${user_id}`;
      let ret_count = await queryOne(query1);
      if( ret_count && ret_count.scan_count >= 10){
        res.json( { 
          code: CODE_ERROR, 
          msg: '您已超过今日AI识别次数', 
          data: err
        });
        return;
      }
      let now = Math.floor(Date.now() / 1000);
      if( !g_access_token || now >= g_expire_time - 60){
        let ret = await getAccessToken();
        g_access_token = ret.access_token;
        g_expire_time = now + parseInt(ret.expires_in);
      }
      if( g_access_token){
        //console.log( g_access_token, g_expire_time);
        let ret = await getOCR(image, g_access_token);
        if( ret.words_result){
          //console.log(ret);
          const query3 = `insert into sys_scanlog(user_id) values (${user_id})`;
          await querySql(query3);
          res.json({ 
            code: CODE_SUCCESS, 
            data: ret.words_result 
          })
        }else{
          res.json( { 
            code: CODE_ERROR, 
            msg: 'call ocr error', 
            data: ret
          });
        }
      }else{
        res.json( { 
          code: CODE_ERROR, 
          msg: 'call token error', 
          data: ret
        });
      }
    }catch( err){
      console.log(err);
      res.json( { 
        code: CODE_ERROR, 
        msg: 'request error', 
        data: err
      });
    }
  }
}

// 编辑生词本
async function editNewWordBook(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    
    let { id, name} = req.body;
    let query = `update sys_newword set name='${name}'`;
    query += ` where id='${id}'`;
    
    try{
      let data = await querySql(query);
      // console.log('编辑设备===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '更新数据失败', 
          data: null 
        })
      } else {
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '更新数据成功', 
          data: null 
        })
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '更新数据失败', 
        data: err 
      })
    }
  }
}

// 添加生词本
async function addNewWordBook(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { user_id, name='默认生词本' } = req.body;
    const query = `insert into sys_newword(user_id,name,words) values('${user_id}', '${name}', '')`;
    try{  
      let data = await querySql(query);
      // console.log('添加任务===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '添加数据失败', 
          data: null 
        })
      } else {
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '添加数据成功', 
          data: null 
        })
      }
    }catch( err){
      res.json({ 
        code: CODE_ERROR, 
        msg: '添加数据失败', 
        data: err 
      })
    }
  }
}

// 删除生词本
async function deleteNewWordBook(req, res, next) {
  const err = validationResult(req);
  if (!err.isEmpty()) {
    const [{ msg }] = err.errors;
    next(boom.badRequest(msg));
  } else {
    let { id } = req.body;

    const query = `update sys_newword set delete_flag=1 where id='${id}'`;
    try{
      let data = await querySql(query)
      // console.log('删除用户===', data);
      if (!data || data.affectedRows === 0) {
        res.json({ 
          code: CODE_ERROR, 
          msg: '删除数据失败', 
          data: null 
        })
      } else {
        res.json({ 
          code: CODE_SUCCESS, 
          msg: '删除数据成功', 
          data: null 
        })
      }
    } catch( err) {
      res.json({ 
        code: CODE_ERROR, 
        msg: '删除数据失败', 
        data: err 
      })
    }
  }
}

module.exports = {
  editNewWord,
  getNewWordList,
  aiOCR,
  addNewWordBook,
  editNewWordBook,
  deleteNewWordBook
}
